package com.zdy.im.user.facade;

import com.sixeco.framework.core.db.IterableConverter;
import com.sixeco.framework.core.redis.RedisClusterServer;
import com.sixeco.framework.core.redis.RedisKeys;
import com.sixeco.framework.core.redis.RedisUtil;
import com.zdy.im.chat.ChatMessageBody;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.user.dto.response.ImRoomInfoResponseDto;
import com.zdy.im.user.dto.response.ImRoomUserShipResponseDto;
import com.zdy.im.user.dto.response.UserInfoResponseDto;
import com.zdy.im.user.service.*;
import com.zdy.im.user.vo.response.ImChatMessageShowResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.tio.utils.json.Json;

import java.util.*;


/**   
 * @Title: ImChatMessageFacade.java
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0  
 *  <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 * @Description: TODO(说明) 对象缓存统一模板实现类;  
 */
 
@Component
public class ImChatMessageFacade {

	@Autowired
	private ImChatMessageService  imChatMessageService;

	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private ImRoomUserShipService imRoomUserShipService;

	@Autowired
	private RedisClusterServer redisClusterServer;

	@Autowired
	private ImMessageReadService imMessageReadService;

	@Autowired
	private ImRoomInfoService imRoomInfoService;



	public List<ImChatMessageShowResponseVo> getUserChatMessageList(long userId) {
		List<ImChatMessageShowResponseVo> voList = new ArrayList<>();
		UserInfoResponseDto userInfo = userInfoService.getUserInfoById(userId);
		if(userInfo == null){
			return voList;
		}
		Map<Integer , Map<Long , Long>> readMap = imMessageReadService.getImMessageReadMapByUserId(userId);
		Map<Long, Long> userMap = readMap.get(ImMessageTypeEnum.Single.getKey());
		Map<Long, Long> groupMap = readMap.get(ImMessageTypeEnum.Group.getKey());
		String formKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER, userId);
		Map<String,String> chatMap =  redisClusterServer.hgetAll(formKey);
		List<ChatMessageBody> list = new ArrayList<>();
		Set<Long> uIds = new HashSet<>();
		if(chatMap != null || !chatMap.isEmpty()){
			setMessage(chatMap , list , userMap ,userId , ImMessageTypeEnum.Single.getKey()  , uIds);
		}
		setMessageUserImg(list , uIds , userId);
		List<ImRoomUserShipResponseDto> roomUserShipList = imRoomUserShipService.getImRoomUserShipByUserId(userId);
		if(roomUserShipList.isEmpty()){
			return sortMessageList(list , voList);
		}
		Set<String> set = new HashSet<>();
		roomUserShipList.forEach(r -> set.add(String.valueOf(r.getRoomId())));
		String roomKey = RedisUtil.formatKey(RedisKeys.MQ_CONSUMER , "roomKey");
		Map<String , String> roomMap =  redisClusterServer.hmget( roomKey , set  ,String.class);
//		setMessage(roomMap , list , groupMap ,userId , ImMessageTypeEnum.Group.getKey() , false , null);
		setRoomMessage(roomMap , list , groupMap ,userId , ImMessageTypeEnum.Group.getKey());
		return sortMessageList(list , voList);
	}


	//设置用户头像
	private void setMessageUserImg(List<ChatMessageBody> list, Set<Long> uIds , long userId) {
		if(uIds.isEmpty()){
			return;
		}
		Map<Long,UserInfoResponseDto> map = userInfoService.getUserInfoByIds(uIds);
		if(map == null || map.isEmpty()){
			return;
		}
		list.forEach( msg ->{
			if(userId == msg.getSendUserId()){
				UserInfoResponseDto dto = map.get(msg.getToId());
				if(dto != null){
					msg.setToUserImg(dto.getHeadImg());
					msg.setToUserName(dto.getUserName());
				}
			}else{
				UserInfoResponseDto dto = map.get(msg.getSendUserId());
				if(dto != null){
					msg.setSendUserImg(dto.getHeadImg());
					msg.setSendUserName(dto.getUserName());
				}
			}
		});
	}

	private void setMessage(Map<String, String> chatMap, List<ChatMessageBody> list ,Map<Long, Long> userMap , long userId , int type , Set<Long> uIds) {
		for(String str  : chatMap.values()){
			ChatMessageBody body = Json.toBean( str , ChatMessageBody.class);
			body.setType(type);
			if(body.getSendUserId() != userId && userMap != null){
				Long gId = userMap.get(body.getMessageId());
				if(null != gId && gId >= body.getGlobalId()){
					body.setReadStatus(1);
				}
				uIds.add(body.getSendUserId());
			}else{
				uIds.add(body.getToId());
			}
			list.add(body);
		}
	}

	private void setRoomMessage(Map<String, String> roomMap, List<ChatMessageBody> list, Map<Long, Long> groupMap, long userId, int type) {
		if(roomMap == null || roomMap.isEmpty()){
			return;
		}
		Set<Long> roomIds = new HashSet<>();
		List<ChatMessageBody> roomList = new ArrayList<>();
		for(String str  : roomMap.values()){
			ChatMessageBody body = Json.toBean( str , ChatMessageBody.class);
			body.setType(type);
			long id = body.getMessageId();
			if(id < 1){
				id = body.getToId();
			}
			roomIds.add(id);
			body.setMessageId(id);
			roomList.add(body);
		}
		Map<Long, ImRoomInfoResponseDto> map = imRoomInfoService.getRoomInfoByIds(roomIds);
		roomList.forEach( r ->{
			ImRoomInfoResponseDto imRoom = map.get(r.getMessageId());
			if(imRoom != null){
				r.setToUserName(imRoom.getRoomName());
				r.setToUserImg(imRoom.getRoomImg());
			}
			list.add(r);
		});

	}

	private List<ImChatMessageShowResponseVo> sortMessageList(List<ChatMessageBody> list , List<ImChatMessageShowResponseVo> voList) {
		if(list.isEmpty()){
			return voList;
		}
		list.sort((a , b) -> Long.compare( b.getGlobalId() , a.getGlobalId()));
		voList = IterableConverter.convertList(list,ImChatMessageShowResponseVo.class);
		return voList;
	}
}
